package com.example.bookmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bookmanagement.dto.BookQueryDTO;
import com.example.bookmanagement.entity.Book;
import com.example.bookmanagement.mapper.BookMapper;
import com.example.bookmanagement.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Override
    @Cacheable("books")
    public IPage<Book> getBooksByPage(Page<Book> page, BookQueryDTO queryDTO) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        if (queryDTO.getBookname() != null && !queryDTO.getBookname().isEmpty()) {
            wrapper.like("bookname", queryDTO.getBookname());
        }
        if (queryDTO.getAuthor() != null && !queryDTO.getAuthor().isEmpty()) {
            wrapper.like("author", queryDTO.getAuthor());
        }
        if (queryDTO.getPublishDate() != null && !queryDTO.getPublishDate().isEmpty()) {
            wrapper.eq("publish_date", queryDTO.getPublishDate());
        }
        return bookMapper.selectPage(page, wrapper);
    }

    @Override
    @Cacheable(value = "books", key = "#id")
    public Optional<Book> getBookById(Long id) {
        return Optional.ofNullable(bookMapper.selectById(id));
    }

    @Override
    @CacheEvict(value = "books", allEntries = true)
    public Book saveBook(Book book) {
        bookMapper.insert(book);
        return book;
    }

    @Override
    @CacheEvict(value = "books", allEntries = true)
    public void deleteBook(Long id) {
        bookMapper.deleteById(id);
    }

    @Override
    @CacheEvict(value = "books", allEntries = true)
    public Book updateBook(Long id, Book book) {
        book.setId(id);
        bookMapper.updateById(book);
        return book;
    }
}    